package com.itheima.d8_tcp5;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 目标：完成TCP通信快速入门-服务端开发：要求实现与多个客户端同时通信。
 */
class Server {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(50);

        System.out.println("-----服务端启动成功-------");
        //创建ServerSocket的对象，同时为服务端注册端口。
        ServerSocket serverSocket = new ServerSocket(8080);

        while (true) {
            //接受浏览器的连接
            Socket socket = serverSocket.accept();

            pool.execute(new ResponseData(socket));

            /*pool.execute(()->{
                try {
                    //获取输出流，给浏览器响应数据
                    OutputStream netOut = socket.getOutputStream();
                    //把基本流封装为打印流，目的是让我们输出数据更加方便了
                    PrintStream ps = new PrintStream(netOut);
                    //给浏览器响应数据要先把协议数据写出
                    ps.println("HTTP/1.1 200 OK");
                    ps.println("Content-Type:text/html;charset=UTF-8");
                    ps.println(); //换行 ---> 协议和内容的分割
                    ps.println("<h1>黑马程序员666</h1>");
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });*/
        }
    }
}


class ResponseData implements Runnable {
    private final Socket socket;

    public ResponseData(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //获取输出流，给浏览器响应数据
            OutputStream netOut = socket.getOutputStream();
            //把基本流封装为打印流，目的是让我们输出数据更加方便了
            PrintStream ps = new PrintStream(netOut);
            //给浏览器响应数据要先把协议数据写出
            ps.println("HTTP/1.1 200 OK");
            ps.println("Content-Type:text/html;charset=UTF-8");
            ps.println(); //换行 ---> 协议和内容的分割
            ps.println("<h1>黑马程序员666</h1>");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}












